package com.jyy.prefabricated.controller;

import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.entity.CourseFile;
import com.jyy.prefabricated.service.BosService;
import com.jyy.prefabricated.service.CourseFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

/**
 * 课程文件
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class CourseFileController {

    @Autowired
    private CourseFileService courseFileService;

    @Autowired
    private BosService bosService;

    /**
     * 上传课程文件
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/course-file")
    public AjaxResult insert(@RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
        CourseFile courseFile = new CourseFile();
        if(file != null){
            log.info("REST request to upload course file:{}",file.getOriginalFilename(),file.getSize());
            String url = "";
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String objectName = UUID.randomUUID().toString().replace("-","") + substring;
            url = bosService.putObject(file, objectName);
//            Encoder encoder = new Encoder();
//            it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(file);
//            long ls = m.getDuration();
            courseFile.setName(originalFilename);
            courseFile.setSize((double)file.getSize());
            courseFile.setPath(url);
        } else {
            log.info("REST request to upload course file type:video");
        }
        int id = courseFileService.insert(courseFile);
        CourseFile result = courseFileService.selectById(id);
        return AjaxResult.success(result);
    }


    /**
     * 删除课程文件
     * @param id
     * @return
     */
    @DeleteMapping("/course-file/{id}")
    public AjaxResult deleteById(@PathVariable Integer id){
        log.info("Rest request to delete course file by id:{}",id);
        int row = courseFileService.delete(id);
        if(row > 0){

            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }


}
